import json
import re
import os
import datetime
from django.shortcuts import render, HttpResponse, redirect
from django.views import View
from apps.cmdb import models as db_cmdb
from apps.rbac import models as db_rabc
from apps.logs import models as db_log
from plugins.public import encryption
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from plugins.public import page as pg
from django.utils.decorators import method_decorator
from apps.rbac.extra_views import login_check, perms_check
from wsshOps.settings import BASE_DIR


class GroupView(View):
    """
    资产视图
    """
    @method_decorator(login_check)
    @method_decorator(perms_check)
    def dispatch(self, request, *args, **kwargs):
        return super(GroupView, self).dispatch(request, *args, **kwargs)

    def get(self, request, page=1):
        caption = "主机组"
        db_obj = db_cmdb.AssetGroup.objects.all().order_by('id')
        if db_obj:
            pagesize = 15
            paginator = Paginator(db_obj, pagesize)
            # 从前端获取当前的页码数,默认为1
            # 把当前的页码数转换成整数类型
            currentPage = int(page)
            page_nums = paginator.num_pages
            page_list = pg.control(currentPage, page_nums)
            try:
                data_list = paginator.page(page)  # 获取当前页码的记录
            except PageNotAnInteger:
                data_list = paginator.page(1)  # 如果用户输入的页码不是整数时,显示第1页的内容
            except EmptyPage:
                data_list = paginator.page(paginator.num_pages)
        else:
            data_list = None
        return render(request, "asset/group_list.html", locals())


    def post(self, request):
        """添加主机组"""
        group_name = request.POST.get("group_name")
        group_msg = request.POST.get("group_msg")
        group_obj = db_cmdb.AssetGroup(group_name=group_name, group_msg=group_msg)
        group_obj.save()
        ret = {"status": "True", "info": "添加成功"}
        return HttpResponse(json.dumps(ret, ensure_ascii=False))

    def put(self, request):
        req_info = eval(request.body.decode())
        group_id = req_info.get("group_id")
        group_name = req_info.get("group_name")
        group_msg = req_info.get("group_msg")
        action = req_info.get("action", None)
        if action:
            """修改主机组"""
            group_obj = db_cmdb.AssetGroup.objects.get(id=group_id)
            group_obj.group_name = group_name
            group_obj.group_msg = group_msg
            group_obj.save()
            ret = {"status": "True", "info": "修改成功"}
            data = json.dumps(ret)
            return HttpResponse(data)
        else:
            """获取主机组信息"""
            group_obj = db_cmdb.AssetGroup.objects.get(id=group_id)
            info_json = {'group_id': group_obj.id, 'group_name': group_obj.group_name, 'group_msg': group_obj.group_msg}
            ret = {"status": "True", "info": info_json}
            data = json.dumps(ret)
        return HttpResponse(data)

    def delete(self, request):
        """删除"""
        req_info = eval(request.body.decode())
        group_id = req_info.get("group_id")
        db_cmdb.AssetGroup.objects.get(id=group_id).delete()
        ret = {"status": "True", "info": "已删除"}
        data = json.dumps(ret)
        return HttpResponse(data)



class IdcView(View):
    """
    资产视图
    """
    @method_decorator(login_check)
    @method_decorator(perms_check)
    def dispatch(self, request, *args, **kwargs):
        return super(IdcView, self).dispatch(request, *args, **kwargs)

    def get(self, request, page=1):
        caption = "机房列表"
        db_obj = db_cmdb.IDC.objects.all().order_by('id')
        if db_obj:
            pagesize = 15
            paginator = Paginator(db_obj, pagesize)
            # 从前端获取当前的页码数,默认为1
            # 把当前的页码数转换成整数类型
            currentPage = int(page)
            page_nums = paginator.num_pages
            page_list = pg.control(currentPage, page_nums)
            try:
                data_list = paginator.page(page)  # 获取当前页码的记录
            except PageNotAnInteger:
                data_list = paginator.page(1)  # 如果用户输入的页码不是整数时,显示第1页的内容
            except EmptyPage:
                data_list = paginator.page(paginator.num_pages)
        else:
            data_list = None
        return render(request, "asset/idc_list.html", locals())

    def post(self, request):
        """添加IDC"""
        idc_name = request.POST.get("idc_name")
        idc_msg = request.POST.get("idc_msg")
        idc_obj = db_cmdb.IDC(idc_name=idc_name, idc_msg=idc_msg)
        idc_obj.save()
        ret = {"status": "True", "info": "添加成功"}
        return HttpResponse(json.dumps(ret, ensure_ascii=False))

    def put(self, request):
        req_info = eval(request.body.decode())
        idc_id = req_info.get("idc_id")
        idc_name = req_info.get("idc_name")
        idc_msg = req_info.get("idc_msg")
        action = req_info.get("action", None)
        if action:
            """修改IDC"""
            idc_obj = db_cmdb.IDC.objects.get(id=idc_id)
            idc_obj.idc_name = idc_name
            idc_obj.idc_msg = idc_msg
            idc_obj.save()
            ret = {"status": "True", "info": "修改成功"}
            data = json.dumps(ret)
            return HttpResponse(data)
        else:
            """获取IDC信息"""
            idc_obj = db_cmdb.IDC.objects.get(id=idc_id)
            info_json = {'idc_id': idc_obj.id, 'idc_name': idc_obj.idc_name, 'idc_msg': idc_obj.idc_msg}
            ret = {"status": "True", "info": info_json}
            data = json.dumps(ret)
        return HttpResponse(data)

    def delete(self, request):
        """删除"""
        req_info = eval(request.body.decode())
        idc_id = req_info.get("idc_id")
        db_cmdb.IDC.objects.get(id=idc_id).delete()
        ret = {"status": "True", "info": "已删除"}
        data = json.dumps(ret)
        return HttpResponse(data)


class AssetView(View):
    """
    资产视图
    """

    @method_decorator(login_check)
    @method_decorator(perms_check)
    def dispatch(self, request, *args, **kwargs):
        return super(AssetView, self).dispatch(request, *args, **kwargs)

    def get(self, request, page=1):
        caption = "资产列表"
        if request.session['is_superuser'] == "1":
            db_obj = db_cmdb.Asset.objects.all().order_by('asset_group_id', '-asset_status')
        else:
            role_id = request.session["role_id"]
            role_obj = db_rabc.Role.objects.get(id=role_id)
            db_obj = role_obj.asset.all().order_by('id')

        if db_obj:
            pagesize = 15
            paginator = Paginator(db_obj, pagesize)
            # 从前端获取当前的页码数,默认为1
            # 把当前的页码数转换成整数类型
            currentPage = int(page)
            page_nums = paginator.num_pages
            page_list = pg.control(currentPage, page_nums)
            try:
                data_list = paginator.page(page)  # 获取当前页码的记录
            except PageNotAnInteger:
                data_list = paginator.page(1)  # 如果用户输入的页码不是整数时,显示第1页的内容
            except EmptyPage:
                data_list = paginator.page(paginator.num_pages)
        else:
            data_list = None

        idc_obj = db_cmdb.IDC.objects.all()
        group_obj = db_cmdb.AssetGroup.objects.all()

        return render(request, "asset/asset_list.html", locals())


    def post(self, request):
        admin_ip = request.POST.get("admin_ip")
        login_port = request.POST.get("login_port")
        login_user = request.POST.get("login_user")
        login_passwd = request.POST.get("login_passwd")
        login_id_rsa = request.POST.get("login_id_rsa")
        connect_method = request.POST.get("connect_method")
        asset_group = request.POST.get("asset_group")
        asset_idc = request.POST.get("asset_idc")
        asset_msg = request.POST.get("asset_msg")
        # 加密密码
        str_key = db_rabc.Dict.objects.get(dict_key="ENCRYPT_KEY").dict_val
        pc = encryption.prpcrypt(str_key)  # 初始化密钥
        aes_passwd = pc.encrypt(login_passwd)

        asset_obj = db_cmdb.Asset(admin_ip=admin_ip, asset_arp=admin_ip,
                                  asset_group_id=asset_group, idc_id=asset_idc, asset_msg=asset_msg,
                                  login_user=login_user,
                                  login_port=login_port, login_passwd=aes_passwd, connect_method=connect_method,
                                  login_id_rsa=login_id_rsa)
        asset_obj.save()

        # if connect_method == "SaltStack":
        #     src_file = os.path.join(BASE_DIR, "plugins", "scripts", "salt_install.sh")
        #     dest_file = "/opt/salt_install.sh"
        #     cmd = "sh /opt/salt_install.sh"
        # else:
        #     src_file = os.path.join(BASE_DIR, "plugins", "scripts", "rsakey_add.sh")
        #     dest_file = "/opt/rsakey_add.sh"
        #     cmd = "sh /opt/rsakey_add.sh"
        #
        # tk = connect_config.delay(admin_ip, login_port, login_user, login_passwd, login_id_rsa, src_file, dest_file,
        #                           cmd, connect_method)
        #
        # task_obj = db_log.Tasks(task_name="服务器连接配置:{}".format(admin_ip), task_id=tk.id, status=tk.state,
        #                         exec_user=request.session["username"])
        # task_obj.save()

        ret = {"status": "True", "info": "添加成功"}
        data = json.dumps(ret)
        return HttpResponse(data)

    def put(self, request):
        data = request.body.decode()
        data = data.replace("null", "None")
        req_info = eval(data)
        asset_id = req_info.get("asset_id")
        admin_ip = req_info.get("admin_ip")
        login_port = req_info.get("login_port")
        login_user = req_info.get("login_user")
        login_passwd = req_info.get("login_passwd")
        login_id_rsa = req_info.get("login_id_rsa")
        connect_method = req_info.get("connect_method")
        asset_group = req_info.get("asset_group")
        asset_idc = req_info.get("asset_idc")
        asset_msg = req_info.get("asset_msg")
        action = req_info.get("action", None)
        if action:
            """修改服务器信息"""
            # 加密密码
            str_key = db_rabc.Dict.objects.get(dict_key="ENCRYPT_KEY").dict_val
            pc = encryption.prpcrypt(str_key)
            aes_passwd = pc.encrypt(login_passwd)
            asset_obj = db_cmdb.Asset.objects.get(id=asset_id)
            asset_obj.admin_ip = admin_ip
            asset_obj.asset_group_id = asset_group
            asset_obj.idc_id = asset_idc
            asset_obj.asset_msg = asset_msg
            asset_obj.connect_method = connect_method
            asset_obj.login_port = login_port
            asset_obj.login_user = login_user
            asset_obj.login_passwd = aes_passwd
            asset_obj.login_id_rsa = login_id_rsa
            asset_obj.save()
            ret = {"status": "True", "info": "修改成功"}
            data = json.dumps(ret)
            return HttpResponse(data)
        else:
            """获取修改信息"""
            asset_info = db_cmdb.Asset.objects.get(id=asset_id)
            # 密码解密
            str_key = db_rabc.Dict.objects.get(dict_key="ENCRYPT_KEY").dict_val
            pc = encryption.prpcrypt(str_key)
            passwd = asset_info.login_passwd.strip("b").strip("'").encode(encoding="utf-8")
            de_passwd = pc.decrypt(passwd).decode()

            info_json = {'asset_id': asset_info.id, 'admin_ip': asset_info.admin_ip,
                         'login_port': asset_info.login_port,
                         'login_user': asset_info.login_user, 'connect_method': asset_info.connect_method,
                         'login_passwd': de_passwd,
                         'asset_group': asset_info.asset_group_id,
                         'asset_idc': asset_info.idc_id, 'asset_msg': asset_info.asset_msg,
                         "login_id_rsa": asset_info.login_id_rsa}

            ret = {"status": "True", "info": info_json}
            data = json.dumps(ret)
            return HttpResponse(data)

    def delete(self, request):
        """删除服务器"""
        req_info = eval(request.body.decode())
        asset_id = req_info.get("asset_id")
        db_cmdb.Asset.objects.get(id=asset_id).delete()
        ret = {"status": "True", "info": "已删除"}
        data = json.dumps(ret)
        return HttpResponse(data)


@login_check
def GetAssetIp(request,ip):
    caption = "资产列表"
    db_obj = db_cmdb.Asset.objects.filter(admin_ip=ip).order_by('asset_group_id', '-id')
    if db_obj:
        pagesize = 15
        paginator = Paginator(db_obj, pagesize)
        # 从前端获取当前的页码数,默认为1
        # 把当前的页码数转换成整数类型
        currentPage = int(1)
        page_nums = paginator.num_pages
        page_list = pg.control(currentPage, page_nums)
        try:
            data_list = paginator.page(1)  # 获取当前页码的记录
        except PageNotAnInteger:
            data_list = paginator.page(1)  # 如果用户输入的页码不是整数时,显示第1页的内容
        except EmptyPage:
            data_list = paginator.page(paginator.num_pages)
    else:
        data_list = None

    idc_obj = db_cmdb.IDC.objects.all()
    group_obj = db_cmdb.AssetGroup.objects.all()
    phpmyadmin = db_rabc.Dict.objects.get(dict_key="PHPMYADMIN").dict_val
    return render(request, "asset/asset_list.html", locals())